package com.xingqing.service.impl;

import com.xingqing.config.FileStorageConfig;
import com.xingqing.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnProperty(name = "file.storage.type", havingValue = "local", matchIfMissing = true)
public class LocalFileStorageService implements FileStorageService {

    private final FileStorageConfig.Local localConfig;

    public LocalFileStorageService(FileStorageConfig fileStorageConfig) {
        this.localConfig = fileStorageConfig.getLocal();
    }

    @Override
    public String upload(MultipartFile file, String fileType) throws Exception {
        // 获取原始文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成新的文件名
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String fileName = fileType + "_" + UUID.randomUUID().toString().replace("-", "") + "_" + timestamp + extension;

        // 创建文件类型目录
        File typeDirectory = new File(localConfig.getUploadDir() + "/" + fileType).getAbsoluteFile();
        if (!typeDirectory.exists()) {
            typeDirectory.mkdirs();
            log.info("创建{}目录: {}", fileType, typeDirectory.getAbsolutePath());
        }

        // 保存文件
        File destinationFile = new File(typeDirectory, fileName);
        log.info("保存文件到: {}", destinationFile.getAbsolutePath());
        file.transferTo(destinationFile);

        // 生成访问路径
        String filePath = localConfig.getUrlPrefix() + "/" + fileType + "/" + fileName;
        log.info("文件上传成功，访问路径: {}", filePath);

        return filePath;
    }

    @Override
    public void delete(String fileUrl) throws Exception {
        if (fileUrl == null || !fileUrl.startsWith(localConfig.getUrlPrefix())) {
            log.warn("无效的文件URL: {}", fileUrl);
            return;
        }

        // 将URL转换为文件路径
        String relativePath = fileUrl.substring(localConfig.getUrlPrefix().length());
        File file = new File(localConfig.getUploadDir() + relativePath);

        if (file.exists() && file.delete()) {
            log.info("文件删除成功: {}", file.getAbsolutePath());
        } else {
            log.warn("文件删除失败或不存在: {}", file.getAbsolutePath());
        }
    }
}